package com.hongru.mms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hongru.constant.DictConstant;
import com.hongru.ebean.EbeanUtil;
import com.hongru.exception.JeecgOrmException;
import com.hongru.mms.entity.MmsSmsLog;
import com.hongru.mms.entity.MmsSmsTemplate;
import com.hongru.mms.entity.dto.SendSmsDto;
import com.hongru.mms.service.MmsSmsService;
import com.hongru.mms.util.AliCloudSmsUtil;
import com.hongru.vo.Result;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description
 * @Copyright (c) 1998-2022 北京新鸿儒世纪网络技术有限公司 All Rights Reserved.
 * @Url https://www.xinhongru.com
 * @ClassName MmsSmsService
 * @Author salter <salter@vip.163.com>
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2022/4/22 14:26
 */
@Service
public class MmsSmsServiceImpl implements MmsSmsService {
    /**
     * 阿里云：alicloud 腾讯云：qcloud
     */
    @Value(value = "${jo.sms.type}")
    private String type;

    @Override
    public Result sendSms(SendSmsDto sendSmsDto) {
        MmsSmsTemplate smsTemplate = EbeanUtil.initExpressionList(MmsSmsTemplate.class).idEq(sendSmsDto.getSmsTemplateId()).findOne();
        if (null == smsTemplate) {
            throw new JeecgOrmException("未配置模板");
        }
        asyncSendSms(sendSmsDto, smsTemplate);
        return Result.OK();
    }

    @Async
    public Result asyncSendSms(SendSmsDto sendSmsDto, MmsSmsTemplate smsTemplate) {
        String result = "";
        String[] phones = sendSmsDto.getPhone().split(",");

        //替换短信发送内容
        //阿里云短信参数替换对象
        JSONObject templateParamJson = new JSONObject();

        Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}");
        String templateContent = smsTemplate.getContent();
        Matcher matcher = pattern.matcher(templateContent);
        int findIndex = 0;
        while (matcher.find()) {
            if (ArrayUtils.isEmpty(sendSmsDto.getParams())) {
                throw new JeecgOrmException("params 参数不能为空");
            } else if (sendSmsDto.getParams().length > findIndex) {
                templateContent = templateContent.replace(matcher.group(0), sendSmsDto.getParams()[findIndex]);
                templateParamJson.put(matcher.group(1), sendSmsDto.getParams()[findIndex]);
                findIndex++;
            } else {
                throw new JeecgOrmException("params 参数个数与短信模板的参数个数不匹配");
            }
        }

        for (int i = 0; i < phones.length; i++) {
            MmsSmsLog smsLogEntity = new MmsSmsLog();
            smsLogEntity.setSmsTemplateId(smsTemplate.getId());
            smsLogEntity.setContent(templateContent);
            smsLogEntity.setPhone(phones[i]);
            smsLogEntity.setSendStatus(0);
            if (DictConstant.CLOUD_TYPE_ALICLOUD.equals(type)) {
                result = AliCloudSmsUtil.sendSms(smsTemplate.getCloudCode(), phones[i], templateParamJson.toJSONString());
                JSONObject jsonObject = JSONObject.parseObject(result);
                if ("OK".equals(jsonObject.getString("code"))) {
                    smsLogEntity.setSendStatus(1);
                }
            }
            if (DictConstant.CLOUD_TYPE_QCLOUD.equals(type)) {
               /* result = QCloudSmsUtil.sendSms(smsTemplate.getCloudCode(), phones[i], sendSmsDto.getParams());
                JSONObject jsonObject = JSONObject.parseObject(result);
                if("OK".equals(jsonObject.getString("errmsg"))){
                    smsLogEntity.setSendStatus(true);
                }*/
            }
            smsLogEntity.setSendResult(result);
            smsLogEntity.save();
        }
        return Result.OK();
    }


}
